<?php

namespace App\Modules\Order;

use App\Modules\Order\Models\Order;
use Carbon\Carbon;
use Illuminate\Console\Scheduling\Schedule as BaseSchedule;
use Illuminate\Support\Facades\Log;

class Schedule
{
    public static function invoke(BaseSchedule $schedule)
    {
        $schedule->call([self::class, 'close'])->everyMinute()->name('关闭未支付订单');
        $schedule->call([self::class, 'delClosed'])->dailyAt('02:00')->name('删除关闭的订单');
        $schedule->call([self::class, 'confirm'])->hourly()->name('自动确认收货');
    }

    public static function close()
    {
        Order::query()
            ->where('status', Order::STATUS_INIT)
            ->where('created_at', "<", Carbon::now()->subMinutes(2 * 60)->toDateTimeString())
            ->lockForUpdate()
            ->each(function (Order $item) {
                $item->close();
            });
    }

    public static function delClosed()
    {
        Order::query()
            ->where('status', Order::STATUS_CLOSE)
            ->where('created_at', "<", now()->startOfDay()->toDateTimeString())
            ->orderBy('id')
            ->each(function ($item) {
                $item->delete();
            });
    }

    public static function confirm()
    {
        Order::query()
            ->where('status', Order::STATUS_PAID)
            ->where('is_finish', 1)
            ->where('buyer_confirm', 0)
            ->where('updated_at', '<', now()->subHours(48)->toDateTimeString())
            ->orderBy('id')
            ->each(function ($item) {
                $item->buyer_confirm = 1;
                $item->save();
            });
    }
}
